package com.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.act.ChatAct;
import com.act.Friend_NewAct;
import com.act.MainAct;
import com.act.MessageDetailAct;
import com.adapter.ChatAllHistoryAdapter;
import com.common.Constant;
import com.control.UserControl;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.exceptions.EaseMobException;
import com.umeng.analytics.MobclickAgent;
import com.xike.kyt.R;
import com.mUI.MessageDialog;

public class MessageFragment extends BaseFragment {

	private ListView listView;
	private ChatAllHistoryAdapter adapter;
	private boolean hidden;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.frag_message, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		listView = (ListView) getView().findViewById(R.id.list);

		List<EMConversation> conversationList = loadConversationsWithRecentChat();
		if (conversationList != null && conversationList.size() > 0) {
			adapter = new ChatAllHistoryAdapter(getActivity(), 1, conversationList);
			// 设置adapter
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					EMConversation conversation = adapter.getItem(position);
					String strSender = conversation.getUserName();
					Intent it;
					if (strSender.equals(Constant.CHAT_USER_ADMIN)) {
						it = new Intent(getActivity(), MessageDetailAct.class);
						it.putExtra("sender", strSender);
					} else {
						try { // 申请加为好友
							String strTitle = conversation.getLastMessage().getStringAttribute("title");
							if (strTitle.equals(Constant.APPLY_FRIEND)) {
								it = new Intent(getActivity(), Friend_NewAct.class);
								startActivity(it);
								conversation.resetUnsetMsgCount();
								return;
							}
						} catch (EaseMobException e) {
						}

						// 其他信息
						it = new Intent(getActivity(), ChatAct.class);
						it.putExtra("userId", strSender);
						String username = "";
						try {
							EMMessage msg = conversation.getLastMessage();
							username = msg.getStringAttribute("sender");
							if (username.equals(UserControl.getLoginUserName())) {
								username = msg.getStringAttribute("to");
							}
						} catch (EaseMobException e) {
							Log.e("MessageFragment", "sender is not found");
						}
						it.putExtra("userName", username);

					}
					startActivity(it);
				}
			});
			listView.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
					final MessageDialog dialog = new MessageDialog(getActivity());
					dialog.show();
					String username = "";
					final EMConversation conversation = adapter.getItem(position);
					try {
						EMMessage msg = conversation.getLastMessage();
						username = msg.getStringAttribute("sender");
						if (username.equals(UserControl.getLoginUserName())) {
							username = msg.getStringAttribute("to");
						}
					} catch (EaseMobException e) {
						Log.e("MessageFragment", "sender is not found");
					}
					dialog.setUserName(username);
					dialog.setOnDeleteClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// 删除此会话
							EMChatManager.getInstance().deleteConversation(conversation.getUserName(), conversation.isGroup());
							adapter.remove(conversation);
							adapter.notifyDataSetChanged();
							((MainAct) getActivity()).updateUnreadLabel();
							dialog.cancel();

						}
					});
					return true;
				}
			});
		} else {
			showNoDataView();
		}

	}

	/**
	 * 刷新页面
	 */
	public void refresh() {
		List<EMConversation> conversationList = loadConversationsWithRecentChat();
		if (conversationList != null && conversationList.size() > 0) {
			adapter = new ChatAllHistoryAdapter(getActivity(), R.layout.listitem_message, conversationList);
			listView.setAdapter(adapter);
			getView().findViewById(R.id.layout_nodata).setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
			adapter.notifyDataSetChanged();
		} else {
			showNoDataView();
		}

	}

	private void showNoDataView() {
		getView().findViewById(R.id.layout_nodata).setVisibility(View.VISIBLE);
		listView.setVisibility(View.GONE);
		((ImageView) getView().findViewById(R.id.layout_nodata_img)).setImageResource(R.drawable.default_nodata_message);
		((TextView) getView().findViewById(R.id.layout_nodata_tv_tips)).setText("没有任何消息");
	}

	/**
	 * 获取所有会话
	 * 
	 * @param context
	 * @return
	 */
	private List<EMConversation> loadConversationsWithRecentChat() {
		// 获取所有会话，包括陌生人
		Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations();
		List<EMConversation> conversationList = new ArrayList<EMConversation>();
		// 过滤掉messages size为0的conversation
		for (EMConversation conversation : conversations.values()) {
			if (conversation.getAllMessages().size() != 0)
				conversationList.add(conversation);
		}
		// 排序
		sortConversationByLastChatTime(conversationList);
		return conversationList;
	}

	/**
	 * 根据最后一条消息的时间排序
	 * 
	 * @param usernames
	 */
	private void sortConversationByLastChatTime(List<EMConversation> conversationList) {
		Collections.sort(conversationList, new Comparator<EMConversation>() {
			@Override
			public int compare(final EMConversation con1, final EMConversation con2) {

				EMMessage con2LastMessage = con2.getLastMessage();
				EMMessage con1LastMessage = con1.getLastMessage();
				if (con2LastMessage.getMsgTime() == con1LastMessage.getMsgTime()) {
					return 0;
				} else if (con2LastMessage.getMsgTime() > con1LastMessage.getMsgTime()) {
					return 1;
				} else {
					return -1;
				}
			}

		});
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		this.hidden = hidden;
		if (!hidden) {
			refresh();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (!hidden) {
			refresh();
		}
		MobclickAgent.onPageStart("MessageFragment"); // 统计页面
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("MessageFragment");
	}

}
